package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.common.*;
import com.shop.common.result.Result;
import com.shop.common.result.util.ResultModel;
import com.shop.dto.CommodityDto;
import com.shop.dto.SelectCommodityByWarehouseDto;
import com.shop.entity.*;
import com.shop.mapper.CommodityDoMapper;
import com.shop.mapper.CommodityWarehouseRelationDoMapper;
import com.shop.mapper.WarehouseInfoDoMapper;
import com.shop.mapper.ext.CommodityDoMapperExt;
import com.shop.mapper.ext.FactoryCommodityExtendDoMapperExt;
import com.shop.service.CommodityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.vo.commodity.UpdateCommodityVo;
import com.shop.vo.commodity.AddCommodityVo;
import com.shop.vo.seller.SelectCommodityByWarehouseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;


import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 靳 旺
 * @since 2020-12-17
 */
@Slf4j
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityDoMapper, CommodityDo> implements CommodityService {

    @Autowired
    private CommodityDoMapperExt commodityDoMapperExt;

    @Autowired
    private CommodityWarehouseRelationDoMapper commodityWarehouseRelationDoMapper;

    @Autowired
    private WarehouseInfoDoMapper warehouseInfoDoMapper;

    @Autowired
    private FactoryCommodityExtendDoMapperExt factoryCommodityExtendDoMapperExt;


    /**
     * 查询商品
     *
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public ResultModel getCommodityList(Integer page, Integer size) throws Exception {
        List<CommodityDto> commodityDos = commodityDoMapperExt.getUserList();
//        commodityDos.stream().forEach(CommodityDto::getCommodityName);
        PageHelper.startPage(page, size);
        PageInfo pageInfo = new PageInfo<>(commodityDos);
        log.info(page.toString());
        log.info(size.toString());
        System.out.printf("1111", commodityDos);
        return Result.successResultModel(pageInfo);
    }

    /**
     * 搜索商品
     *
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public ResultModel search(String name) throws Exception {
//        QueryWrapper<CommodityDo> queryWrapper = new QueryWrapper<CommodityDo>();
//        queryWrapper.like("commodity_name",name);
//        List<CommodityDo> userInfoList = baseMapper.selectList(queryWrapper);
//        QueryWrapper<CommodityDto> queryWrapper = new QueryWrapper<CommodityDto>();
//        queryWrapper.like("commodity_name",name);
        List<CommodityDto> userInfoList = commodityDoMapperExt.search(name);

//        commodityDos.stream().forEach(k -> log.info(k.getName()));
//        PageHelper.startPage(page, size);
//        PageInfo pageInfo = new PageInfo<>(commodityDos);
//        log.info(page.toString());
//        log.info(size.toString());
//        System.out.printf("1111", commodityDos);
        return Result.successResultModel(userInfoList);
    }

    /**
     * 删除商品
     *
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public ResultModel delCommodity(Integer id) throws Exception {
        Integer aa = baseMapper.deleteById(id);
        return Result.successResultModel(aa);
    }

    /**
     * 修改商品
     *
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public ResultModel updateCommodity(UpdateCommodityVo updateCommodityVo) throws Exception {
        CommodityDo commodity = new CommodityDo();
        commodity.setCommodityNo(updateCommodityVo.getCommodityNo());
//        commodity.setCommodityName(updateCommodityVo.getCommodityName());
//        commodity.setTitle(updateCommodityVo.getTitle());
        commodity.setPkCommodityId(updateCommodityVo.getId());
//        commodity.setPrice(updateCommodityVo.getPrice());
//        commodity.setSize(updateCommodityVo.getSize());
        Integer result = baseMapper.updateById(commodity);
        System.out.println("result: " + result);
        log.info("result: " + result);
        return Result.successResultModel(result);
    }

    /**
     * 添加商品
     *
     * @param addCommodityVo
     * @return
     * @throws Exception
     */
    @Override
    public ResultModel addCommodity(AddCommodityVo addCommodityVo) throws Exception {
        CommodityDo commodityDo = new CommodityDo();
//        commodityDo.setCommodityName(addCommodityVo.getCommodityName());
//        commodityDo.setPrice(addCommodityVo.getPrice());
//        commodityDo.setSize(addCommodityVo.getSize());
        commodityDo.setCommodityNo(addCommodityVo.getCommodityNo());
//        commodityDo.setTitle(addCommodityVo.getTitle());
//        clientDo.setIsDel("n");
        if (baseMapper.insert(commodityDo) <= 0) throw new Exception("添加失败！");
//        return commodityDo;
        return Result.successResultModel();
    }

    @Override
    public ResultModel selectCommodityByWarehouse(SelectCommodityByWarehouseVo selectCommodityByWarehouseVo) throws Exception {
        /* 1、检查参数 */
        selectCommodityByWarehouseVo.checkParameters();
        /* 2、验证仓库是否存在 */
        this.selectWarehousInfoById(selectCommodityByWarehouseVo.getPkWarehouseInfoId());
        /* 3、查询商品列表 */
        List<SelectCommodityByWarehouseDto> selectCommodityByWarehouseDtoList = this.batchSelectCommodity(selectCommodityByWarehouseVo.getPkWarehouseInfoId());
        /* 4、查询商品扩展信息并分页 */
        PageHelper.startPage(selectCommodityByWarehouseVo.getPageIndex(), selectCommodityByWarehouseVo.getPageSize());
        List<SelectCommodityByWarehouseDto> selectCommodityByWarehouseDtos = this.batchFactoryCommodityExtend(selectCommodityByWarehouseDtoList);
        PageInfo<SelectCommodityByWarehouseDto> pageInfo = new PageInfo<>(selectCommodityByWarehouseDtos);
        return Result.successResultModel(pageInfo);
    }

    /**
     * 通过id 查询仓库
     *
     * @param id
     * @return
     */
    private Boolean selectWarehousInfoById(Long id) {
        QueryWrapper<WarehouseInfoDo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pk_warehouse_info_id", id);
        WarehouseInfoDo warehouseInfoDo = warehouseInfoDoMapper.selectOne(queryWrapper);
        Assert.notNull(warehouseInfoDo, "没有找到您仓库！");
        return true;
    }

    /**
     * 查询商品列表
     *
     * @param pkWarehouseInfoId
     * @return
     * @throws Exception
     */
    private List<SelectCommodityByWarehouseDto> batchSelectCommodity(Long pkWarehouseInfoId) throws Exception {
        /* 1、查询商品仓库关联表*/
        QueryWrapper<CommodityWarehouseRelationDo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fk_warehouse_info_id", pkWarehouseInfoId);
        List<CommodityWarehouseRelationDo> commodityWarehouseRelationDoList = commodityWarehouseRelationDoMapper.selectList(queryWrapper);
        if (commodityWarehouseRelationDoList.size() <= 0) throw new Exception("没有找到关联商品！");
        Map<Long, List<CommodityWarehouseRelationDo>> map = commodityWarehouseRelationDoList.stream().collect(Collectors.groupingBy(CommodityWarehouseRelationDo::getFkCommodityId));
        /* 2、过滤商品主键 */
        List<CommodityWarehouseRelationDo> distinctClass = commodityWarehouseRelationDoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CommodityWarehouseRelationDo::getFkCommodityId))), ArrayList::new));
        List<CommodityDo> commodityDoList = distinctClass.stream().map(k ->{
            CommodityDo commodityDo= new CommodityDo();
            commodityDo.setPkCommodityId(k.getFkCommodityId());
            commodityDo.setCreateId(TokenUtil.getUserId());
            return commodityDo;
        }).collect(Collectors.toList());
        /* 3、查询商品集合 */
        List<SelectCommodityByWarehouseDto> selectCommodityByWarehouseDtoList = baseMapper.selectBatchIds(commodityDoList).stream().map(k -> {
            SelectCommodityByWarehouseDto selectCommodityByWarehouseDto = new SelectCommodityByWarehouseDto();
            ObjectUtil.annotationToObject(k, selectCommodityByWarehouseDto);
          List<CommodityWarehouseRelationDo> commodityWarehouseRelationDos =  map.get(selectCommodityByWarehouseDto.getPkCommodityId());
          if (commodityWarehouseRelationDos.size() > 0 ) selectCommodityByWarehouseDto.setCurrentCommodityNumber(commodityWarehouseRelationDos.get(0).getCurrentCommodityNumber());
            return selectCommodityByWarehouseDto;
        }).collect(Collectors.toList());
        return selectCommodityByWarehouseDtoList;
    }

    /**
     * 查询商品扩展信息
     *
     * @param selectCommodityByWarehouseDtoList
     * @return
     * @throws Exception
     */
    private List<SelectCommodityByWarehouseDto> batchFactoryCommodityExtend(List<SelectCommodityByWarehouseDto> selectCommodityByWarehouseDtoList) throws Exception {
        List<Long> commodityIds = selectCommodityByWarehouseDtoList.stream().map(SelectCommodityByWarehouseDto::getPkCommodityId).collect(Collectors.toList());
        List<FactoryCommodityExtendDo> factoryCommodityExtendDoList = factoryCommodityExtendDoMapperExt.selectFactoryCommodity(commodityIds);
        Map<Long, List<FactoryCommodityExtendDo>> map = factoryCommodityExtendDoList.stream().collect(Collectors.groupingBy(FactoryCommodityExtendDo::getFkCommodityId));
        return selectCommodityByWarehouseDtoList.stream().map(k -> {
            List<FactoryCommodityExtendDo> factoryCommodityExtendDos = map.get(k.getPkCommodityId());
            if (factoryCommodityExtendDos.size() > 0) {
                ObjectUtil.annotationToObject(factoryCommodityExtendDos.get(0), k);
            }
            return k;
        }).collect(Collectors.toList());
    }

}
